home *** CD-ROM | disk | FTP | other *** search
/ Languguage OS 2 / Languguage OS II Version 10-94 (Knowledge Media)(1994).ISO / gnu / elispman.lha / elispman / elisp-6 (.txt) < prev    next >
GNU Info File  |  1993-06-01  |  49KB  |  953 lines

  1. This is Info file elisp, produced by Makeinfo-1.55 from the input file
  2. elisp.texi.
  3.    This is edition 2.0 of the GNU Emacs Lisp Reference Manual, for
  4. Emacs Version 19.
  5.    Published by the Free Software Foundation, 675 Massachusetts Avenue,
  6. Cambridge, MA 02139 USA
  7.    Copyright (C) 1990, 1991, 1992, 1993 Free Software Foundation, Inc.
  8.    Permission is granted to make and distribute verbatim copies of this
  9. manual provided the copyright notice and this permission notice are
  10. preserved on all copies.
  11.    Permission is granted to copy and distribute modified versions of
  12. this manual under the conditions for verbatim copying, provided that
  13. the entire resulting derived work is distributed under the terms of a
  14. permission notice identical to this one.
  15.    Permission is granted to copy and distribute translations of this
  16. manual into another language, under the above conditions for modified
  17. versions, except that this permission notice may be stated in a
  18. translation approved by the Foundation.
  19. File: elisp,  Node: Array Functions,  Next: Vectors,  Prev: Arrays,  Up: Sequences Arrays Vectors
  20. Functions that Operate on Arrays
  21. ================================
  22.    In this section, we describe the functions that accept both strings
  23. and vectors.
  24.  - Function: arrayp OBJECT
  25.      This function returns `t' if OBJECT is an array (i.e., either a
  26.      vector or a string).
  27.           (arrayp [a])
  28.           => t
  29.           (arrayp "asdf")
  30.           => t
  31.  - Function: aref ARRAY INDEX
  32.      This function returns the INDEXth element of ARRAY.  The first
  33.      element is at index zero.
  34.           (setq primes [2 3 5 7 11 13])
  35.                => [2 3 5 7 11 13]
  36.           (aref primes 4)
  37.                => 11
  38.           (elt primes 4)
  39.                => 11
  40.           
  41.           (aref "abcdefg" 1)
  42.                => 98           ; `b' is ASCII code 98.
  43.      See also the function `elt', in *Note Sequence Functions::.
  44.  - Function: aset ARRAY INDEX OBJECT
  45.      This function sets the INDEXth element of ARRAY to be OBJECT.  It
  46.      returns OBJECT.
  47.           (setq w [foo bar baz])
  48.                => [foo bar baz]
  49.           (aset w 0 'fu)
  50.                => fu
  51.           w
  52.                => [fu bar baz]
  53.           
  54.           (setq x "asdfasfd")
  55.                => "asdfasfd"
  56.           (aset x 3 ?Z)
  57.                => 90
  58.           x
  59.                => "asdZasfd"
  60.      If ARRAY is a string and OBJECT is not a character, a
  61.      `wrong-type-argument' error results.
  62.  - Function: fillarray ARRAY OBJECT
  63.      This function fills the array ARRAY with pointers to OBJECT,
  64.      replacing any previous values.  It returns ARRAY.
  65.           (setq a [a b c d e f g])
  66.                => [a b c d e f g]
  67.           (fillarray a 0)
  68.                => [0 0 0 0 0 0 0]
  69.           a
  70.                => [0 0 0 0 0 0 0]
  71.           (setq s "When in the course")
  72.                => "When in the course"
  73.           (fillarray s ?-)
  74.                => "------------------"
  75.      If ARRAY is a string and OBJECT is not a character, a
  76.      `wrong-type-argument' error results.
  77.    The general sequence functions `copy-sequence' and `length' are
  78. often useful for objects known to be arrays.  *Note Sequence
  79. Functions::.
  80. File: elisp,  Node: Vectors,  Prev: Array Functions,  Up: Sequences Arrays Vectors
  81. Vectors
  82. =======
  83.    Arrays in Lisp, like arrays in most languages, are blocks of memory
  84. whose elements can be accessed in constant time.  A "vector" is a
  85. general-purpose array; its elements can be any Lisp objects.  (The other
  86. kind of array provided in Emacs Lisp is the "string", whose elements
  87. must be characters.)  The main uses of vectors in Emacs are as syntax
  88. tables (vectors of integers) and keymaps (vectors of commands).  They
  89. are also used internally as part of the representation of a
  90. byte-compiled function; if you print such a function, you will see a
  91. vector in it.
  92.    The indices of the elements of a vector are numbered starting with
  93. zero in Emacs Lisp.
  94.    Vectors are printed with square brackets surrounding the elements in
  95. their order.  Thus, a vector containing the symbols `a', `b' and `c' is
  96. printed as `[a b c]'.  You can write vectors in the same way in Lisp
  97. input.
  98.    A vector, like a string or a number, is considered a constant for
  99. evaluation: the result of evaluating it is the same vector.  The
  100. elements of the vector are not evaluated.  *Note Self-Evaluating
  101. Forms::.
  102.    Here are examples of these principles:
  103.      (setq avector [1 two '(three) "four" [five]])
  104.           => [1 two (quote (three)) "four" [five]]
  105.      (eval avector)
  106.           => [1 two (quote (three)) "four" [five]]
  107.      (eq avector (eval avector))
  108.           => t
  109.    Here are some functions that relate to vectors:
  110.  - Function: vectorp OBJECT
  111.      This function returns `t' if OBJECT is a vector.
  112.           (vectorp [a])
  113.                => t
  114.           (vectorp "asdf")
  115.                => nil
  116.  - Function: vector &rest OBJECTS
  117.      This function creates and returns a vector whose elements are the
  118.      arguments, OBJECTS.
  119.           (vector 'foo 23 [bar baz] "rats")
  120.                => [foo 23 [bar baz] "rats"]
  121.           (vector)
  122.                => []
  123.  - Function: make-vector INTEGER OBJECT
  124.      This function returns a new vector consisting of INTEGER elements,
  125.      each initialized to OBJECT.
  126.           (setq sleepy (make-vector 9 'Z))
  127.                => [Z Z Z Z Z Z Z Z Z]
  128.  - Function: vconcat &rest SEQUENCES
  129.      This function returns a new vector containing all the elements of
  130.      the SEQUENCES.  The arguments SEQUENCES may be lists, vectors, or
  131.      strings.  If no SEQUENCES are given, an empty vector is returned.
  132.      The value is a newly constructed vector that is not `eq' to any
  133.      existing vector.
  134.           (setq a (vconcat '(A B C) '(D E F)))
  135.                => [A B C D E F]
  136.           (eq a (vconcat a))
  137.                => nil
  138.           (vconcat)
  139.                => []
  140.           (vconcat [A B C] "aa" '(foo (6 7)))
  141.                => [A B C 97 97 foo (6 7)]
  142.      When an argument is an integer (not a sequence of integers), it is
  143.      converted to a string of digits making up the decimal printed
  144.      representation of the integer.  This special case exists for
  145.      compatibility with Mocklisp, and we don't recommend you take
  146.      advantage of it.  If you want to convert an integer in this way,
  147.      use `format' (*note Formatting Strings::.) or `int-to-string'
  148.      (*note String Conversion::.).
  149.      For other concatenation functions, see `mapconcat' in *Note
  150.      Mapping Functions::, `concat' in *Note Creating Strings::, and
  151.      `append' in *Note Building Lists::.
  152.    The `append' function may be used to convert a vector into a list
  153. with the same elements (*note Building Lists::.):
  154.      (setq avector [1 two (quote (three)) "four" [five]])
  155.           => [1 two (quote (three)) "four" [five]]
  156.      (append avector nil)
  157.           => (1 two (quote (three)) "four" [five])
  158. File: elisp,  Node: Symbols,  Next: Evaluation,  Prev: Sequences Arrays Vectors,  Up: Top
  159. Symbols
  160. *******
  161.    A "symbol" is an object with a unique name.  This chapter describes
  162. symbols, their components, and how they are created and interned.
  163. Property lists are also described.  The uses of symbols as variables
  164. and as function names are described in separate chapters; see *Note
  165. Variables::, and *Note Functions::.  For the precise syntax for
  166. symbols, see *Note Symbol Type::.
  167.    You can test whether an arbitrary Lisp object is a symbol with
  168. `symbolp':
  169.  - Function: symbolp OBJECT
  170.      This function returns `t' if OBJECT is a symbol, `nil' otherwise.
  171. * Menu:
  172. * Symbol Components::        Symbols have names, values, function definitions
  173.                                and property lists.
  174. * Definitions::              A definition says how a symbol will be used.
  175. * Creating Symbols::         How symbols are kept unique.
  176. * Property Lists::           Each symbol has a property list
  177.                                for recording miscellaneous information.
  178. File: elisp,  Node: Symbol Components,  Next: Definitions,  Prev: Symbols,  Up: Symbols
  179. Symbol Components
  180. =================
  181.    Each symbol has four components (or "cells"), each of which
  182. references another object:
  183. Print name
  184.      The "print name cell" holds a string which names the symbol for
  185.      reading and printing.  See `symbol-name' in *Note Creating
  186.      Symbols::.
  187. Value
  188.      The "value cell" holds the current value of the symbol as a
  189.      variable.  When a symbol is used as a form, the value of the form
  190.      is the contents of the symbol's value cell.  See `symbol-value' in
  191.      *Note Accessing Variables::.
  192. Function
  193.      The "function cell" holds the function definition of the symbol.
  194.      When a symbol is used as a function, its function definition is
  195.      used in its place.  This cell is also used to make a symbol stand
  196.      for a keymap or a keyboard macro, for editor command execution.
  197.      Because each symbol has separate value and function cells,
  198.      variables and function names do not conflict.  See
  199.      `symbol-function' in *Note Function Cells::.
  200. Property list
  201.      The "property list cell" holds the property list of the symbol.
  202.      See `symbol-plist' in *Note Property Lists::.
  203.    The print name cell always holds a string, and cannot be changed.
  204. The other three cells can be set individually to any specified Lisp
  205. object.
  206.    The print name cell holds the string that is the name of the symbol.
  207. Since symbols are represented textually by their names, it is important
  208. not to have two symbols with the same name.  The Lisp reader ensures
  209. this: every time it reads a symbol, it looks for an existing symbol with
  210. the specified name before it creates a new one.  (In GNU Emacs Lisp,
  211. this is done with a hashing algorithm that uses an obarray; see *Note
  212. Creating Symbols::.)
  213.    In normal usage, the function cell usually contains a function or
  214. macro, as that is what the Lisp interpreter expects to see there (*note
  215. Evaluation::.).  Keyboard macros (*note Keyboard Macros::.), keymaps
  216. (*note Keymaps::.) and autoload objects (*note Autoloading::.) are also
  217. sometimes stored in the function cell of symbols.  We often refer to
  218. "the function `foo'" when we really mean the function stored in the
  219. function cell of the symbol `foo'.  We make the distinction only when
  220. necessary.
  221.    Similarly, the property list cell normally holds a correctly
  222. formatted property list (*note Property Lists::.), as a number of
  223. functions expect to see a property list there.
  224.    The function cell or the value cell may be "void", which means that
  225. the cell does not reference any object.  (This is not the same thing as
  226. holding the symbol `void', nor the same as holding the symbol `nil'.)
  227. Examining the value of a cell which is void results in an error, such
  228. as `Symbol's value as variable is void'.
  229.    The four functions `symbol-name', `symbol-value', `symbol-plist',
  230. and `symbol-function' return the contents of the four cells.  Here as
  231. an example we show the contents of the four cells of the symbol
  232. `buffer-file-name':
  233.      (symbol-name 'buffer-file-name)
  234.           => "buffer-file-name"
  235.      (symbol-value 'buffer-file-name)
  236.           => "/gnu/elisp/symbols.texi"
  237.      (symbol-plist 'buffer-file-name)
  238.           => (variable-documentation 29529)
  239.      (symbol-function 'buffer-file-name)
  240.           => #<subr buffer-file-name>
  241. Because this symbol is the variable which holds the name of the file
  242. being visited in the current buffer, the value cell contents we see are
  243. the name of the source file of this chapter of the Emacs Lisp Manual.
  244. The property list cell contains the list `(variable-documentation
  245. 29529)' which tells the documentation functions where to find
  246. documentation about `buffer-file-name' in the `DOC' file.  (29529 is
  247. the offset from the beginning of the `DOC' file where the documentation
  248. for the function begins.)  The function cell contains the function for
  249. returning the name of the file.  `buffer-file-name' names a primitive
  250. function, which has no read syntax and prints in hash notation (*note
  251. Primitive Function Type::.).  A symbol naming a function written in
  252. Lisp would have a lambda expression (or a byte-code object) in this
  253. cell.
  254. File: elisp,  Node: Definitions,  Next: Creating Symbols,  Prev: Symbol Components,  Up: Symbols
  255. Defining Symbols
  256. ================
  257.    A "definition" in Lisp is a special form that announces your
  258. intention to use a certain symbol in a particular way.  In Emacs Lisp,
  259. you can define a symbol as a variable, or define it as a function (or
  260. macro), or both independently.
  261.    A definition construct typically specifies a value or meaning for the
  262. symbol for one kind of use, plus documentation for its meaning when used
  263. in this way.  Thus, when you define a symbol as a variable, you can
  264. supply an initial value for the variable, plus documentation for the
  265. variable.
  266.    `defvar' and `defconst' are special forms that define a symbol as a
  267. global variable.  They are documented in detail in *Note Defining
  268. Variables::.
  269.    `defun' defines a symbol as a function, creating a lambda expression
  270. and storing it in the function cell of the symbol.  This lambda
  271. expression thus becomes the function definition of the symbol.  (The
  272. term "function definition", meaning the contents of the function cell,
  273. is derived from the idea that `defun' gives the symbol its definition
  274. as a function.)  *Note Functions::.
  275.    `defmacro' defines a symbol as a macro.  It creates a macro object
  276. and stores it in the function cell of the symbol.  Note that a given
  277. symbol can be a macro or a function, but not both at once, because both
  278. macro and function definitions are kept in the function cell, and that
  279. cell can hold only one Lisp object at any given time.  *Note Macros::.
  280.    In GNU Emacs Lisp, a definition is not required in order to use a
  281. symbol as a variable or function.  Thus, you can make a symbol a global
  282. variable with `setq', whether you define it first or not.  The real
  283. purpose of definitions is to guide programmers and programming tools.
  284. They inform programmers who read the code that certain symbols are
  285. *intended* to be used as variables, or as functions.  In addition,
  286. utilities such as `etags' and `make-docfile' can recognize definitions,
  287. and add the appropriate information to tag tables and the
  288. `emacs/etc/DOC-VERSION' file. *Note Accessing Documentation::.
  289. File: elisp,  Node: Creating Symbols,  Next: Property Lists,  Prev: Definitions,  Up: Symbols
  290. Creating and Interning Symbols
  291. ==============================
  292.    To understand how symbols are created in GNU Emacs Lisp, you must
  293. know how Lisp reads them.  Lisp must ensure that it finds the same
  294. symbol every time it reads the same set of characters.  Failure to do
  295. so would cause complete confusion.
  296.    When the Lisp reader encounters a symbol, it reads all the characters
  297. of the name.  Then it "hashes" those characters to find an index in a
  298. table called an "obarray".  Hashing is an efficient method of looking
  299. something up.  For example, instead of searching a telephone book cover
  300. to cover when looking up Jan Jones, you start with the J's and go from
  301. there.  That is a simple version of hashing.  Each element of the
  302. obarray is a "bucket" which holds all the symbols with a given hash
  303. code; to look for a given name, it is sufficient to look through all
  304. the symbols in the bucket for that name's hash code.
  305.    If a symbol with the desired name is found, then it is used.  If no
  306. such symbol is found, then a new symbol is created and added to the
  307. obarray bucket.  Adding a symbol to an obarray is called "interning"
  308. it, and the symbol is then called an "interned symbol".  In Emacs Lisp,
  309. a symbol may be interned in only one obarray--if you try to intern the
  310. same symbol in more than one obarray, you will get unpredictable
  311. results.
  312.    It is possible for two different symbols to have the same name in
  313. different obarrays; these symbols are not `eq' or `equal'.  However,
  314. this normally happens only as part of abbrev definition (*note
  315. Abbrevs::.).
  316.      Common Lisp note: in Common Lisp, a symbol may be interned in
  317.      several obarrays at once.
  318.    If a symbol is not in the obarray, then there is no way for Lisp to
  319. find it when its name is read.  Such a symbol is called an "uninterned
  320. symbol" relative to the obarray.  An uninterned symbol has all the
  321. other characteristics of symbols.
  322.    In Emacs Lisp, an obarray is represented as a vector.  Each element
  323. of the vector is a bucket; its value is either an interned symbol whose
  324. name hashes to that bucket, or 0 if the bucket is empty.  Each interned
  325. symbol has an internal link (invisible to the user) to the next symbol
  326. in the bucket.  Because these links are invisible, there is no way to
  327. scan the symbols in an obarray except using `mapatoms' (below).  The
  328. order of symbols in a bucket is not significant.
  329.    In an empty obarray, every element is 0, and you can create an
  330. obarray with `(make-vector LENGTH 0)'.  *This is the only valid way to
  331. create an obarray.*  Prime numbers as lengths tend to result in good
  332. hashing; lengths one less than a power of two are also good.
  333.    *Do not try to create an obarray that is not empty.*  This does not
  334. work--only `intern' can enter a symbol in an obarray properly.  Also,
  335. don't try to put into an obarray of your own a symbol that is already
  336. interned in the main obarray, because in Emacs Lisp a symbol cannot be
  337. in two obarrays at once.
  338.    Most of the functions below take a name and sometimes an obarray as
  339. arguments.  A `wrong-type-argument' error is signaled if the name is
  340. not a string, or if the obarray is not a vector.
  341.  - Function: symbol-name SYMBOL
  342.      This function returns the string that is SYMBOL's name.  For
  343.      example:
  344.           (symbol-name 'foo)
  345.                => "foo"
  346.      Changing the string by substituting characters, etc, does change
  347.      the name of the symbol, but fails to update the obarray, so don't
  348.      do it!
  349.  - Function: make-symbol NAME
  350.      This function returns a newly-allocated, uninterned symbol whose
  351.      name is NAME (which must be a string).  Its value and function
  352.      definition are void, and its property list is `nil'.  In the
  353.      example below, the value of `sym' is not `eq' to `foo' because it
  354.      is a distinct uninterned symbol whose name is also `foo'.
  355.           (setq sym (make-symbol "foo"))
  356.                => foo
  357.           (eq sym 'foo)
  358.                => nil
  359.  - Function: intern NAME &optional OBARRAY
  360.      This function returns the interned symbol whose name is NAME.  If
  361.      there is no such symbol in the obarray, a new one is created,
  362.      added to the obarray, and returned.  If OBARRAY is supplied, it
  363.      specifies the obarray to use; otherwise, the value of the global
  364.      variable `obarray' is used.
  365.           (setq sym (intern "foo"))
  366.                => foo
  367.           (eq sym 'foo)
  368.                => t
  369.           
  370.           (setq sym1 (intern "foo" other-obarray))
  371.                => foo
  372.           (eq sym 'foo)
  373.                => nil
  374.  - Function: intern-soft NAME &optional OBARRAY
  375.      This function returns the symbol whose name is NAME, or `nil' if a
  376.      symbol with that name is not found in the obarray.  Therefore, you
  377.      can use `intern-soft' to test whether a symbol with a given name is
  378.      interned.  If OBARRAY is supplied, it specifies the obarray to
  379.      use; otherwise the value of the global variable `obarray' is used.
  380.           (intern-soft "frazzle")        ; No such symbol exists.
  381.                => nil
  382.           (make-symbol "frazzle")        ; Create an uninterned one.
  383.                => frazzle
  384.           (intern-soft "frazzle")        ; That one cannot be found.
  385.                => nil
  386.           (setq sym (intern "frazzle"))  ; Create an interned one.
  387.                => frazzle
  388.           (intern-soft "frazzle")        ; That one can be found!
  389.                => frazzle
  390.           (eq sym 'frazzle)              ; And it is the same one.
  391.                => t
  392.  - Variable: obarray
  393.      This variable is the standard obarray for use by `intern' and
  394.      `read'.
  395.  - Function: mapatoms FUNCTION &optional OBARRAY
  396.      This function applies FUNCTION to every symbol in OBARRAY.  It
  397.      returns `nil'.  If OBARRAY is not supplied, it defaults to the
  398.      value of `obarray', the standard obarray for ordinary symbols.
  399.           (setq count 0)
  400.                => 0
  401.           (defun count-syms (s)
  402.             (setq count (1+ count)))
  403.                => count-syms
  404.           (mapatoms 'count-syms)
  405.                => nil
  406.           count
  407.                => 1871
  408.      See `documentation' in *Note Accessing Documentation::, for another
  409.      example using `mapatoms'.
  410. File: elisp,  Node: Property Lists,  Prev: Creating Symbols,  Up: Symbols
  411. Property Lists
  412. ==============
  413.    A "property list" ("plist" for short) is a list of paired elements
  414. stored in the property list cell of a symbol.  Each of the pairs
  415. associates a property name (usually a symbol) with a property or value.
  416. Property lists are generally used to record information about a
  417. symbol, such as how to compile it, the name of the file where it was
  418. defined, or perhaps even the grammatical class of the symbol
  419. (representing a word) in a language understanding system.
  420.    Character positions in a string or buffer can also have property
  421. lists.  *Note Text Properties::.
  422.    The property names and values in a property list can be any Lisp
  423. objects, but the names are usually symbols.  They are compared using
  424. `eq'.  Here is an example of a property list, found on the symbol
  425. `progn' when the compiler is loaded:
  426.      (lisp-indent-function 0 byte-compile byte-compile-progn)
  427. Here `lisp-indent-function' and `byte-compile' are property names, and
  428. the other two elements are the corresponding values.
  429.    Association lists (*note Association Lists::.) are very similar to
  430. property lists.  In contrast to association lists, the order of the
  431. pairs in the property list is not significant since the property names
  432. must be distinct.
  433.    Property lists are better than association lists when it is necessary
  434. to attach information to various Lisp function names or variables.  If
  435. all the pairs are recorded in one association list, the program will
  436. need to search that entire list each time a function or variable is to
  437. be operated on.  By contrast, if the information is recorded in the
  438. property lists of the function names or variables themselves, each
  439. search will scan only the length of one property list, which is usually
  440. short.  For this reason, the documentation for a variable is recorded in
  441. a property named `variable-documentation'.  The byte compiler likewise
  442. uses properties to record those functions needing special treatment.
  443.    However, association lists have their own advantages.  Depending on
  444. your application, it may be faster to add an association to the front of
  445. an association list than to update a property.  All properties for a
  446. symbol are stored in the same property list, so there is a possibility
  447. of a conflict between different uses of a property name.  (For this
  448. reason, it is a good idea to use property names that are probably
  449. unique, such as by including the name of the library in the property
  450. name.)  An association list may be used like a stack where associations
  451. are pushed on the front of the list and later discarded; this is not
  452. possible with a property list.
  453.  - Function: symbol-plist SYMBOL
  454.      This function returns the property list of SYMBOL.
  455.  - Function: setplist SYMBOL PLIST
  456.      This function sets SYMBOL's property list to PLIST.  Normally,
  457.      PLIST should be a well-formed property list, but this is not
  458.      enforced.
  459.           (setplist 'foo '(a 1 b (2 3) c nil))
  460.                => (a 1 b (2 3) c nil)
  461.           (symbol-plist 'foo)
  462.                => (a 1 b (2 3) c nil)
  463.      For symbols in special obarrays, which are not used for ordinary
  464.      purposes, it may make sense to use the property list cell in a
  465.      nonstandard fashion; in fact, the abbrev mechanism does so (*note
  466.      Abbrevs::.).
  467.  - Function: get SYMBOL PROPERTY
  468.      This function finds the value of the property named PROPERTY in
  469.      SYMBOL's property list.  If there is no such property, `nil' is
  470.      returned.  Thus, there is no distinction between a value of `nil'
  471.      and the absence of the property.
  472.      The name PROPERTY is compared with the existing property names
  473.      using `eq', so any object is a legitimate property.
  474.      See `put' for an example.
  475.  - Function: put SYMBOL PROPERTY VALUE
  476.      This function puts VALUE onto SYMBOL's property list under the
  477.      property name PROPERTY, replacing any previous value.
  478.           (put 'fly 'verb 'transitive)
  479.                =>'transitive
  480.           (put 'fly 'noun '(a buzzing little bug))
  481.                => (a buzzing little bug)
  482.           (get 'fly 'verb)
  483.                => transitive
  484.           (symbol-plist 'fly)
  485.                => (verb transitive noun (a buzzing little bug))
  486. File: elisp,  Node: Evaluation,  Next: Control Structures,  Prev: Symbols,  Up: Top
  487. Evaluation
  488. **********
  489.    The "evaluation" of expressions in Emacs Lisp is performed by the
  490. "Lisp interpreter"--a program that receives a Lisp object as input and
  491. computes its "value as an expression".  The value is computed in a
  492. fashion that depends on the data type of the object, following rules
  493. described in this chapter.  The interpreter runs automatically to
  494. evaluate portions of your program, but can also be called explicitly
  495. via the Lisp primitive function `eval'.
  496. * Menu:
  497. * Intro Eval::  Evaluation in the scheme of things.
  498. * Eval::        How to invoke the Lisp interpreter explicitly.
  499. * Forms::       How various sorts of objects are evaluated.
  500. * Quoting::     Avoiding evaluation (to put constants in the program).
  501. File: elisp,  Node: Intro Eval,  Next: Eval,  Up: Evaluation
  502. Introduction to Evaluation
  503. ==========================
  504.    The Lisp interpreter, or evaluator, is the program which computes
  505. the value of an expression which is given to it.  When a function
  506. written in Lisp is called, the evaluator computes the value of the
  507. function by evaluating the expressions in the function body.  Thus,
  508. running any Lisp program really means running the Lisp interpreter.
  509.    How the evaluator handles an object depends primarily on the data
  510. type of the object.
  511.    A Lisp object which is intended for evaluation is called an
  512. "expression" or a "form".  The fact that expressions are data objects
  513. and not merely text is one of the fundamental differences between
  514. Lisp-like languages and typical programming languages.  Any object can
  515. be evaluated, but in practice only numbers, symbols, lists and strings
  516. are evaluated very often.
  517.    It is very common to read a Lisp expression and then evaluate the
  518. expression, but reading and evaluation are separate activities, and
  519. either can be performed alone.  Reading per se does not evaluate
  520. anything; it converts the printed representation of a Lisp object to the
  521. object itself.  It is up to the caller of `read' whether this object is
  522. a form to be evaluated, or serves some entirely different purpose.
  523. *Note Input Functions::.
  524.    Do not confuse evaluation with command key interpretation.  The
  525. editor command loop translates keyboard input into a command (an
  526. interactively callable function) using the active keymaps, and then
  527. uses `call-interactively' to invoke the command.  The execution of the
  528. command itself involves evaluation if the command is written in Lisp,
  529. but that is not a part of command key interpretation itself.  *Note
  530. Command Loop::.
  531.    Evaluation is a recursive process.  That is, evaluation of a form may
  532. cause `eval' to be called again in order to evaluate parts of the form.
  533. For example, evaluation of a function call first evaluates each
  534. argument of the function call, and then evaluates each form in the
  535. function body.  Consider evaluation of the form `(car x)': the subform
  536. `x' must first be evaluated recursively, so that its value can be
  537. passed as an argument to the function `car'.
  538.    The evaluation of forms takes place in a context called the
  539. "environment", which consists of the current values and bindings of all
  540. Lisp variables.(1)  Whenever the form refers to a variable without
  541. creating a new binding for it, the value of the binding in the current
  542. environment is used.  *Note Variables::.
  543.    Evaluation of a form may create new environments for recursive
  544. evaluation by binding variables (*note Local Variables::.).  These
  545. environments are temporary and will be gone by the time evaluation of
  546. the form is complete.  The form may also make changes that persist;
  547. these changes are called "side effects".  An example of a form that
  548. produces side effects is `(setq foo 1)'.
  549.    Finally, evaluation of one particular function call, `byte-code',
  550. invokes the "byte-code interpreter" on its arguments.  Although the
  551. byte-code interpreter is not the same as the Lisp interpreter, it uses
  552. the same environment as the Lisp interpreter, and may on occasion invoke
  553. the Lisp interpreter.  (*Note Byte Compilation::.)
  554.    The details of what evaluation means for each kind of form are
  555. described below (*note Forms::.).
  556.    ---------- Footnotes ----------
  557.    (1)  This definition of "environment" is specifically not intended
  558. to include all the data which can affect the result of a program.
  559. File: elisp,  Node: Eval,  Next: Forms,  Prev: Intro Eval,  Up: Evaluation
  560.    Most often, forms are evaluated automatically, by virtue of their
  561. occurrence in a program being run.  On rare occasions, you may need to
  562. write code that evaluates a form that is computed at run time, such as
  563. after reading a form from text being edited or getting one from a
  564. property list.  On these occasions, use the `eval' function.
  565.    The functions and variables described in this section evaluate
  566. forms, specify limits to the evaluation process, or record recently
  567. returned values.  Loading a file also does evaluation (*note
  568. Loading::.).
  569.  - Function: eval FORM
  570.      This is the basic function for performing evaluation.  It evaluates
  571.      FORM in the current environment and returns the result.  How the
  572.      evaluation proceeds depends on the type of the object (*note
  573.      Forms::.).
  574.      Since `eval' is a function, the argument expression that appears
  575.      in a call to `eval' is evaluated twice: once as preparation before
  576.      `eval' is called, and again by the `eval' function itself.  Here
  577.      is an example:
  578.           (setq foo 'bar)
  579.                => bar
  580.           (setq bar 'baz)
  581.                => baz
  582.           ;; `eval' receives argument `bar', which is the value of `foo'
  583.           (eval foo)
  584.                => baz
  585.      The number of currently active calls to `eval' is limited to
  586.      `max-lisp-eval-depth' (see below).
  587.  - Command: eval-current-buffer &optional STREAM
  588.      This function evaluates the forms in the current buffer.  It reads
  589.      forms from the buffer and calls `eval' on them until the end of the
  590.      buffer is reached, or until an error is signaled and not handled.
  591.      If STREAM is supplied, the variable `standard-output' is bound to
  592.      STREAM during the evaluation (*note Output Functions::.).
  593.      `eval-current-buffer' always returns `nil'.
  594.  - Command: eval-region START END &optional STREAM
  595.      This function evaluates the forms in the current buffer in the
  596.      region defined by the positions START and END.  It reads forms from
  597.      the region and calls `eval' on them until the end of the region is
  598.      reached, or until an error is signaled and not handled.
  599.      If STREAM is supplied, `standard-output' is bound to it for the
  600.      duration of the command.
  601.      `eval-region' always returns `nil'.
  602.  - Variable: max-lisp-eval-depth
  603.      This variable defines the maximum depth allowed in calls to
  604.      `eval', `apply', and `funcall' before an error is signaled (with
  605.      error message `"Lisp nesting exceeds max-lisp-eval-depth"').
  606.      `eval' is called recursively to evaluate the arguments of Lisp
  607.      function calls and to evaluate bodies of functions.
  608.      This limit, with the associated error when it is exceeded, is one
  609.      way that Lisp avoids infinite recursion on an ill-defined function.
  610.      The default value of this variable is 200.  If you set it to a
  611.      value less than 100, Lisp will reset it to 100 if the given value
  612.      is reached.
  613.      `max-specpdl-size' provides another limit on nesting.  *Note Local
  614.      Variables::.
  615.  - Variable: values
  616.      The value of this variable is a list of values returned by all
  617.      expressions which were read from buffers (including the
  618.      minibuffer), evaluated, and printed.  The elements are in order,
  619.      most recent first.
  620.           (setq x 1)
  621.                => 1
  622.           (list 'A (1+ 2) auto-save-default)
  623.                => (A 3 t)
  624.           values
  625.                => ((A 3 t) 1 ...)
  626.      This variable is useful for referring back to values of forms
  627.      recently evaluated.  It is generally a bad idea to print the value
  628.      of `values' itself, since this may be very long.  Instead, examine
  629.      particular elements, like this:
  630.           ;; Refer to the most recent evaluation result.
  631.           (nth 0 values)
  632.                => (A 3 t)
  633.           ;; That put a new element on,
  634.           ;;   so all elements move back one.
  635.           (nth 1 values)
  636.                => (A 3 t)
  637.           ;; This gets the element that was next-to-last
  638.           ;;   before this example.
  639.           (nth 3 values)
  640.                => 1
  641. File: elisp,  Node: Forms,  Next: Quoting,  Prev: Eval,  Up: Evaluation
  642. Kinds of Forms
  643. ==============
  644.    A Lisp object that is intended to be evaluated is called a "form".
  645. How Emacs evaluates a form depends on its data type.  Emacs has three
  646. different kinds of form that are evaluated differently: symbols, lists,
  647. and "all other types".  All three kinds are described in this section,
  648. starting with "all other types" which are self-evaluating forms.
  649. * Menu:
  650. * Self-Evaluating Forms::   Forms that evaluate to themselves.
  651. * Symbol Forms::            Symbols evaluate as variables.
  652. * Classifying Lists::       How to distinguish various sorts of list forms.
  653. * Function Indirection::    When a symbol appears as the car of a list,
  654.                   we find the real function via the symbol.
  655. * Function Forms::          Forms that call functions.
  656. * Macro Forms::             Forms that call macros.
  657. * Special Forms::           "Special forms" are idiosyncratic primitives,
  658.                               most of them extremely important.
  659. * Autoloading::             Functions set up to load files
  660.                               containing their real definitions.
  661. File: elisp,  Node: Self-Evaluating Forms,  Next: Symbol Forms,  Up: Forms
  662. Self-Evaluating Forms
  663. ---------------------
  664.    A "self-evaluating form" is any form that is not a list or symbol.
  665. Self-evaluating forms evaluate to themselves: the result of evaluation
  666. is the same object that was evaluated.  Thus, the number 25 evaluates to
  667. 25, and the string `"foo"' evaluates to the string `"foo"'.  Likewise,
  668. evaluation of a vector does not cause evaluation of the elements of the
  669. vector--it returns the same vector with its contents unchanged.
  670.      '123               ; An object, shown without evaluation.
  671.           => 123
  672.      123                ; Evaluated as usual---result is the same.
  673.           => 123
  674.      (eval '123)        ; Evaluated ``by hand''---result is the same.
  675.           => 123
  676.      (eval (eval '123)) ; Evaluating twice changes nothing.
  677.           => 123
  678.    It is common to write numbers, characters, strings, and even vectors
  679. in Lisp code, taking advantage of the fact that they self-evaluate.
  680. However, it is quite unusual to do this for types that lack a read
  681. syntax, because it is inconvenient and not very useful; however, it is
  682. possible to put them inside Lisp programs when they are constructed
  683. from subexpressions rather than read.  Here is an example:
  684.      ;; Build such an expression.
  685.      (setq buffer (list 'print (current-buffer)))
  686.           => (print #<buffer eval.texi>)
  687.      ;; Evaluate it.
  688.      (eval buffer)
  689.           -| #<buffer eval.texi>
  690.           => #<buffer eval.texi>
  691. File: elisp,  Node: Symbol Forms,  Next: Classifying Lists,  Prev: Self-Evaluating Forms,  Up: Forms
  692. Symbol Forms
  693. ------------
  694.    When a symbol is evaluated, it is treated as a variable.  The result
  695. is the variable's value, if it has one.  If it has none (if its value
  696. cell is void), an error is signaled.  For more information on the use of
  697. variables, see *Note Variables::.
  698.    In the following example, we set the value of a symbol with `setq'.
  699. When the symbol is later evaluated, that value is returned.
  700.      (setq a 123)
  701.           => 123
  702.      (eval 'a)
  703.           => 123
  704.      a
  705.           => 123
  706.    The symbols `nil' and `t' are treated specially, so that the value
  707. of `nil' is always `nil', and the value of `t' is always `t'.  Thus,
  708. these two symbols act like self-evaluating forms, even though `eval'
  709. treats them like any other symbol.
  710. File: elisp,  Node: Classifying Lists,  Next: Function Indirection,  Prev: Symbol Forms,  Up: Forms
  711. Classification of List Forms
  712. ----------------------------
  713.    A form that is a nonempty list is either a function call, a macro
  714. call, or a special form, according to its first element.  These three
  715. kinds of forms are evaluated in different ways, described below.  The
  716. rest of the list consists of "arguments" for the function, macro or
  717. special form.
  718.    The first step in evaluating a nonempty list is to examine its first
  719. element.  This element alone determines what kind of form the list is
  720. and how the rest of the list is to be processed.  The first element is
  721. *not* evaluated, as it would be in some Lisp dialects including Scheme.
  722. File: elisp,  Node: Function Indirection,  Next: Function Forms,  Prev: Classifying Lists,  Up: Forms
  723. Symbol Function Indirection
  724. ---------------------------
  725.    If the first element of the list is a symbol then evaluation examines
  726. the symbol's function cell, and uses its contents instead of the
  727. original symbol.  If the contents are another symbol, this process,
  728. called "symbol function indirection", is repeated until a non-symbol is
  729. obtained.  *Note Function Names::, for more information about using a
  730. symbol as a name for a function stored in the function cell of the
  731. symbol.
  732.    One possible consequence of this process is an infinite loop, in the
  733. event that a symbol's function cell refers to the same symbol.  Or a
  734. symbol may have a void function cell, causing a `void-function' error.
  735. But if neither of these things happens, we eventually obtain a
  736. non-symbol, which ought to be a function or other suitable object.
  737.    More precisely, we should now have a Lisp function (a lambda
  738. expression), a byte-code function, a primitive function, a Lisp macro, a
  739. special form, or an autoload object.  Each of these types is a case
  740. described in one of the following sections.  If the object is not one of
  741. these types, the error `invalid-function' is signaled.
  742.    The following example illustrates the symbol indirection process.  We
  743. use `fset' to set the function cell of a symbol and `symbol-function'
  744. to get the function cell contents (*note Function Cells::.).
  745. Specifically, we store the symbol `car' into the function cell of
  746. `first', and the symbol `first' into the function cell of `erste'.
  747.      ;; Build this function cell linkage:
  748.      ;;   -------------       -----        -------        -------
  749.      ;;  | #<subr car> | <-- | car |  <-- | first |  <-- | erste |
  750.      ;;   -------------       -----        -------        -------
  751.      (symbol-function 'car)
  752.           => #<subr car>
  753.      (fset 'first 'car)
  754.           => car
  755.      (fset 'erste 'first)
  756.           => first
  757.      (erste '(1 2 3))   ; Call the function referenced by `erste'.
  758.           => 1
  759.    By contrast, the following example calls a function without any
  760. symbol function indirection, because the first element is an anonymous
  761. Lisp function, not a symbol.
  762.      ((lambda (arg) (erste arg))
  763.       '(1 2 3))
  764.           => 1
  765. After that function is called, its body is evaluated; this does involve
  766. symbol function indirection when calling `erste'.
  767.    The built-in function `indirect-function' provides an easy way to
  768. perform symbol function indirection explicitly.
  769.  - Function: indirect-function FUNCTION
  770.      This function returns the meaning of FUNCTION as a function.  If
  771.      FUNCTION is a symbol, then it finds FUNCTION's function definition
  772.      and starts over with that value.  If FUNCTION is not a symbol,
  773.      then it returns FUNCTION itself.
  774.      Here is how you could define `indirect-function' in Lisp:
  775.           (defun indirect-function (function)
  776.             (if (symbolp function)
  777.                 (indirect-function (symbol-function function))
  778.               function))
  779. File: elisp,  Node: Function Forms,  Next: Macro Forms,  Prev: Function Indirection,  Up: Forms
  780. Evaluation of Function Forms
  781. ----------------------------
  782.    If the first element of a list being evaluated is a Lisp function
  783. object, byte-code object or primitive function object, then that list is
  784. a "function call".  For example, here is a call to the function `+':
  785.      (+ 1 x)
  786.    When a function call is evaluated, the first step is to evaluate the
  787. remaining elements of the list in the order they appear.  The results
  788. are the actual argument values, one argument from each element.  Then
  789. the function is called with this list of arguments, effectively using
  790. the function `apply' (*note Calling Functions::.).  If the function is
  791. written in Lisp, the arguments are used to bind the argument variables
  792. of the function (*note Lambda Expressions::.); then the forms in the
  793. function body are evaluated in order, and the result of the last one is
  794. used as the value of the function call.
  795. File: elisp,  Node: Macro Forms,  Next: Special Forms,  Prev: Function Forms,  Up: Forms
  796. Lisp Macro Evaluation
  797. ---------------------
  798.    If the first element of a list being evaluated is a macro object,
  799. then the list is a "macro call".  When a macro call is evaluated, the
  800. elements of the rest of the list are *not* initially evaluated.
  801. Instead, these elements themselves are used as the arguments of the
  802. macro.  The macro definition computes a replacement form, called the
  803. "expansion" of the macro, which is evaluated in place of the original
  804. form.  The expansion may be any sort of form: a self-evaluating
  805. constant, a symbol or a list.  If the expansion is itself a macro call,
  806. this process of expansion repeats until some other sort of form results.
  807.    Normally, the argument expressions are not evaluated as part of
  808. computing the macro expansion, but instead appear as part of the
  809. expansion, so they are evaluated when the expansion is evaluated.
  810.    For example, given a macro defined as follows:
  811.      (defmacro cadr (x)
  812.        (list 'car (list 'cdr x)))
  813. an expression such as `(cadr (assq 'handler list))' is a macro call,
  814. and its expansion is:
  815.      (car (cdr (assq 'handler list)))
  816. Note that the argument `(assq 'handler list)' appears in the expansion.
  817.    *Note Macros::, for a complete description of Emacs Lisp macros.
  818. File: elisp,  Node: Special Forms,  Next: Autoloading,  Prev: Macro Forms,  Up: Forms
  819. Special Forms
  820. -------------
  821.    A "special form" is a primitive function specially marked so that
  822. its arguments are not all evaluated.  Special forms define control
  823. structures or perform variable bindings--things which functions cannot
  824.    Each special form has its own rules for which arguments are evaluated
  825. and which are used without evaluation.  Whether a particular argument is
  826. evaluated may depend on the results of evaluating other arguments.
  827.    Here is a list, in alphabetical order, of all of the special forms in
  828. Emacs Lisp with a reference to where each is described.
  829. `and'
  830.      *note Combining Conditions::.
  831. `catch'
  832.      *note Catch and Throw::.
  833. `cond'
  834.      *note Conditionals::.
  835. `condition-case'
  836.      *note Handling Errors::.
  837. `defconst'
  838.      *note Defining Variables::.
  839. `defmacro'
  840.      *note Defining Macros::.
  841. `defun'
  842.      *note Defining Functions::.
  843. `defvar'
  844.      *note Defining Variables::.
  845. `function'
  846.      *note Anonymous Functions::.
  847.      *note Conditionals::.
  848. `interactive'
  849.      *note Interactive Call::.
  850. `let'
  851. `let*'
  852.      *note Local Variables::.
  853.      *note Combining Conditions::.
  854. `prog1'
  855. `prog2'
  856. `progn'
  857.      *note Sequencing::.
  858. `quote'
  859.      *note Quoting::.
  860. `save-excursion'
  861.      *note Excursions::.
  862. `save-restriction'
  863.      *note Narrowing::.
  864. `save-window-excursion'
  865.      *note Window Configurations::.
  866. `setq'
  867.      *note Setting Variables::.
  868. `setq-default'
  869.      *note Creating Buffer-Local::.
  870. `track-mouse'
  871.      *note Mouse Tracking::.
  872. `unwind-protect'
  873.      *note Nonlocal Exits::.
  874. `while'
  875.      *note Iteration::.
  876. `with-output-to-temp-buffer'
  877.      *note Temporary Displays::.
  878.      Common Lisp note: here are some comparisons of special forms in
  879.      GNU Emacs Lisp and Common Lisp.  `setq', `if', and `catch' are
  880.      special forms in both Emacs Lisp and Common Lisp.  `defun' is a
  881.      special form in Emacs Lisp, but a macro in Common Lisp.
  882.      `save-excursion' is a special form in Emacs Lisp, but doesn't
  883.      exist in Common Lisp.  `throw' is a special form in Common Lisp
  884.      (because it must be able to throw multiple values), but it is a
  885.      function in Emacs Lisp (which doesn't have multiple values).
  886. File: elisp,  Node: Autoloading,  Prev: Special Forms,  Up: Forms
  887. Autoloading
  888. -----------
  889.    The "autoload" feature allows you to call a function or macro whose
  890. function definition has not yet been loaded into Emacs.  When an
  891. autoload object appears as a symbol's function definition and that
  892. symbol is used as a function, Emacs will automatically install the real
  893. definition (plus other associated code) and then call that definition.
  894. (*Note Autoload::.)
  895. File: elisp,  Node: Quoting,  Prev: Forms,  Up: Evaluation
  896. Quoting
  897. =======
  898.    The special form `quote' returns its single argument "unchanged".
  899.  - Special Form: quote OBJECT
  900.      This special form returns OBJECT, without evaluating it.  This
  901.      allows symbols and lists, which would normally be evaluated, to be
  902.      included literally in a program.  (It is not necessary to quote
  903.      numbers, strings, and vectors since they are self-evaluating.)
  904.      Because `quote' is used so often in programs, Lisp provides a
  905.      convenient read syntax for it.  An apostrophe character (`'')
  906.      followed by a Lisp object (in read syntax) expands to a list whose
  907.      first element is `quote', and whose second element is the object.
  908.      Thus, the read syntax `'x' is an abbreviation for `(quote x)'.
  909.      Here are some examples of expressions that use `quote':
  910.           (quote (+ 1 2))
  911.                => (+ 1 2)
  912.           (quote foo)
  913.                => foo
  914.           'foo
  915.                => foo
  916.           ''foo
  917.                => (quote foo)
  918.           '(quote foo)
  919.                => (quote foo)
  920.           ['foo]
  921.                => [(quote foo)]
  922.    Other quoting constructs include `function' (*note Anonymous
  923. Functions::.), which causes an anonymous lambda expression written in
  924. Lisp to be compiled, and ``' (*note Backquote::.), which is used to
  925. quote only part of a list, while computing and substituting other parts.
  926. File: elisp,  Node: Control Structures,  Next: Variables,  Prev: Evaluation,  Up: Top
  927. Control Structures
  928. ******************
  929.    A Lisp program consists of expressions or "forms" (*note Forms::.).
  930. We control the order of execution of the forms by enclosing them in
  931. "control structures".  Control structures are special forms which
  932. control when, whether, or how many times to execute the forms they
  933. contain.
  934.    The simplest control structure is sequential execution: first form
  935. A, then form B, and so on.  This is what happens when you write several
  936. forms in succession in the body of a function, or at top level in a
  937. file of Lisp code--the forms are executed in the order they are
  938. written.  We call this "textual order".  For example, if a function
  939. body consists of two forms A and B, evaluation of the function
  940. evaluates first A and then B, and the function's value is the value of
  941.    Naturally, Emacs Lisp has many kinds of control structures, including
  942. other varieties of sequencing, function calls, conditionals, iteration,
  943. and (controlled) jumps.  The built-in control structures are special
  944. forms since their subforms are not necessarily evaluated.  You can use
  945. macros to define your own control structure constructs (*note
  946. Macros::.).
  947. * Menu:
  948. * Sequencing::             Evaluation in textual order.
  949. * Conditionals::           `if', `cond'.
  950. * Combining Conditions::   `and', `or', `not'.
  951. * Iteration::              `while' loops.
  952. * Nonlocal Exits::         Jumping out of a sequence.
  953.